#include "widgetinversionform.h"
#include "ui_widgetinversionform.h"
#include"../gloab/globalobserver.h"

#include <QSplineSeries>
#include <QDateTimeAxis>
#include <QValueAxis>
#include <QDateTime>
#include <QLegendMarker>
#include <QFileDialog>

WidgetInversionForm::WidgetInversionForm(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::WidgetInversionForm)
{
    ui->setupUi(this);

    //this->InitChart_Temperature_Humidity();
    formInit();
    connect(this, &WidgetInversionForm::Sig_beginInversion, this, &WidgetInversionForm::Slot_inersionCall);

}

WidgetInversionForm::~WidgetInversionForm()
{
    delete ui;
}

void WidgetInversionForm::formInit()
{
    //选择背景文件路径
    connect(ui->btn_backFilePath, &QPushButton::clicked, this, [=](){
        QString path = QFileDialog::getExistingDirectory(this, "选择背景文件目录", QDir::homePath(), QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);
        if(!path.isEmpty()){
            ui->edit_backFilePath->setText(path);
        }
    });

    //选择临时文件路径
    connect(ui->btn_tempFilePath, &QPushButton::clicked, this, [=](){
        QString path = QFileDialog::getExistingDirectory(this, "选择临时文件目录", QDir::homePath());
        if(!path.isEmpty()){
            ui->edit_tempFilePath->setText(path);
        }
    });

    connect(GlobalObserver::getInstance(), &GlobalObserver::Sig_VisibilityProtocol, this, [=](protocol::VisibilityProtocol protocol){
        m_inversion->m_visibility = protocol.m_one_minute_visibility;
        m_inversion->m_visibilityFlag = true;
    });

    connect(GlobalObserver::getInstance(), &GlobalObserver::Sig_GroundWeatherStationProtocol, this, [=](protocol::GroundWeatherStationProtocol protocol){
        m_inversion->m_pressure = protocol.m_pressure;
        m_inversion->m_temperature = protocol.m_temperature;
        m_inversion->m_humidity = protocol.m_humidity;
        m_inversion->m_windSpeed = protocol.m_one_minute_maxWindSpeed;
        m_inversion->m_windDirection = protocol.m_one_minute_windDirection;
        m_inversion->m_groundWeatherStationFlag = true;
    });

    connect(GlobalObserver::getInstance(), &GlobalObserver::Sig_SolarRadioMeterProtocolSTA, this, [=](const protocol::RadioMeterSTAProtocolAll& protocol){
        /*QDateTime midnight = QDateTime(protocol.dateTime.date(), QTime(0, 0, 0));
        long trackTime = protocol.dateTime.msecsTo(midnight);

        inversion->m_trackTimes.push_back(trackTime);
        inversion->m_trackAzims.push_back(protocol.azimuthAngle);
        inversion->m_trackEleveations.push_back(protocol.heightAngle);*/
        m_inversion->m_solorRadioMeterFlag = true;
    });

    connect(GlobalObserver::getInstance(), &GlobalObserver::Sig_SolarRadioMeterProtocolNSU, this, [=](const protocol::RadioMeterNSUProtocolAll& protocol){
        m_inversion->m_lidarFlag = true;
    });
    //获取激光雷达的client和太阳辐射计的port，方便在数据反演时获得一些参数信息，注意在在使用前需要确定是否连接成功
    connect(GlobalObserver::getInstance(), &GlobalObserver::Sig_lidarGetClint, this, [=](QSharedPointer<LidarClient> point){
        m_lidarClient = point;
    });

    connect(GlobalObserver::getInstance(), &GlobalObserver::Sig_SolorRadioMeterSendPortPoint, this, [=](QSharedPointer<QSerialPort> point){
        m_solorPort = point;
    });
}

void WidgetInversionForm::Slot_inersionCall()
{
    bool ok;
    if(ui->edit_backFilePath->text().isEmpty() || ui->edit_tempFilePath->text().isEmpty() || ui->edit_obsAlt->text().isEmpty()){
        qDebug()<<"dir is empety";
        return;
    }
    m_inversion->m_backgroundDataDir = ui->edit_backFilePath->text().toLatin1().data();
    m_inversion->m_tempDir = ui->edit_tempFilePath->text().toLatin1().data();
    m_inversion->m_obsAlt = ui->edit_obsAlt->text().toFloat(&ok);
    if(!ok){
        qDebug()<<"edit_obsAlt to float err";
        return;
    }

    //获取剩余需要的参数，例如从页面上获取的路径，设置的设备摆放高度，气溶胶类型
    //激光雷达部分
    if(!m_lidarClient){
        qDebug()<<"inversionErr : m_lidarClient is nullptr";
        return;
    }
    const QSharedPointer<lidar::RuntimeParamsPackage> PMTState =  m_lidarClient->getPMTState(::lidar::GUID());
    if(!PMTState){
        qDebug()<<"m_lidarClient call getPMTState error";
        return;
    }
    m_inversion->m_lon = PMTState->unitlocation().longitude();
    m_inversion->m_lat = PMTState->unitlocation().latitude();
    m_inversion->m_alt = PMTState->unitlocation().altitude();

    ::lidar::AlgrithmParamsPackage algrithmParamsPackage;
    //0x0400对应消光系数
    algrithmParamsPackage.set_requestedmethods(0x0400);
    const QSharedPointer<lidar::ComputedResult> computedResult = m_lidarClient->getNextComputerData(algrithmParamsPackage);
    if(!computedResult){
        qDebug()<<"m_lidarClient call getNextComputerData error";
        return;
    }
    QVector<float> vec;

    //消光系数，是否可以直接data(0)取到，还需要存入两个高度，不知道是啥高度
    vec.push_back(QString::fromStdString(computedResult->data(0)).toFloat());

    m_inversion->deepinSightCall();

    for(int i = 0; i < m_inversion->m_trackDX; ++i){
        QDateTime dataTime(QDate::currentDate(), QTime(0,0,0).addMSecs(m_inversion->m_deepinsght[i][0]));
        float transmittance = (m_inversion->m_deepinsght[i][4] + m_inversion->m_deepinsght[i][7] + m_inversion->m_deepinsght[i][10])/3;
        float pathRadiance = m_inversion->m_deepinsght[i][5] + m_inversion->m_deepinsght[i][8] + m_inversion->m_deepinsght[i][11];
        float backgroundRadiance = m_inversion->m_deepinsght[i][6] + m_inversion->m_deepinsght[i][9] + m_inversion->m_deepinsght[i][12];
        QString strSql = QString("INSERT INTO \"TESTDBA\".\"inversion\"(\"time\",\"azimuthAngle\",\"heighAngle\",\"distance\",\"transmittance\",\"pathRadiance\",\"backgroundRadiance\")"
                                 "VALUES('%1','%2','%3','%4','%5','%6','%7');").arg(dataTime.toString("yyyyMMdd HHmmss").arg(m_inversion->m_deepinsght[i][1])
                                      .arg(m_inversion->m_deepinsght[i][2]).arg(m_inversion->m_deepinsght[i][3]).arg(transmittance).arg(pathRadiance).arg(backgroundRadiance));
    }


}

// void WidgetInversionForm::InitChart_Temperature_Humidity()
// {
//     m_chart = new QChart();

//     QSplineSeries* m_series = new QSplineSeries(m_chart);
//     m_series->setPen(QPen(QBrush(Qt::blue),2, Qt::PenStyle::SolidLine,
//                                       Qt::PenCapStyle::RoundCap, Qt::PenJoinStyle::RoundJoin));

//     m_chart->addSeries(m_series);


//     // 更改标题颜色和字体大小
//     QFont titleFont("sans-serif", 12, QFont::Bold);
//     m_chart->setTitleFont(titleFont);
//     QBrush titleBrush(Qt::black);
//     m_chart->setTitleBrush(titleBrush);

//     // 设置y轴
//     QValueAxis *axisY_tem = new QValueAxis();
//     axisY_tem->setRange(0, 50);
//     axisY_tem->setTickCount(6);
//     axisY_tem->setLabelFormat("%.2lf");

//     // 设置x轴
//     QDateTimeAxis* axisX = new QDateTimeAxis;
//     axisX->setTickCount(5);
//     axisX->setFormat("hh:mm:ss");
//     axisX->setRange(QDateTime::currentDateTime().addSecs(-60), QDateTime::currentDateTime().addMSecs(500));

//     m_chart->addAxis(axisX, Qt::AlignBottom);
//     m_chart->addAxis(axisY_tem, Qt::AlignmentFlag::AlignLeft);

//     m_series->attachAxis(axisX);
//     m_series->attachAxis(axisY_tem);


//     m_chart->legend()->markers().at(0)->setVisible(true);
//     m_chart->legend()->markers().at(0)->setFont(QFont("微软雅黑",12));
//     m_chart->legend()->markers().at(0)->setPen(QPen(Qt::blue));
//     m_series->setName("透过率");

//     m_chart->legend()->attachToChart();


//     /*
//     connect(this, &InitChart_Temperature_Humidity::updateView, this, [&](int temperature){

//         m_series->append(QDateTime::currentDateTime().toMSecsSinceEpoch(), temperature);
//         if(m_series->count() > 100){
//             m_series->removePoints(0, m_series->count() - 100);
//         }

//         QDateTime start1 = axisX->min().addMSecs(1000);
//         QDateTime end1 = axisX->max().addMSecs(1000);
//         axisX->setRange(start1, end1);
//         ui->graphicsView_tgl->update();
//     });
// */
// }
